// 导入 vue
import { createApp } from "vue";
// 导入 页面组件
import BizhiSwiper from "./components/BizhiSwiper.vue";
import SearchInput from "./components/SearchInput.vue";
import SwitchSearchInput from "./components/SwitchSearchInput.vue";
// 导入 类型
import { ContentScriptContext } from "wxt/client";
import { SearchInputMark, SearchInputMarkType } from "@/common/storage-mark";
import * as wxt from "wxt/storage";
import { convartBgURL } from "@/common";

/** 当前显示的搜索框类型 */
let searchInputType = "system" as SearchInputMarkType;

/** 重置页面样式 */
const resetPageStyle = () => {
  return new Promise((resolve, reject) => {
    // 修改body样式
    document.body.style.overflow = "hidden";
    // 修改 用户登录按钮 样式
    const buttonContainer = document.querySelector(
      "#bookmarkmain .cornerBtnsContainer"
    ) as HTMLElement | null;
    if (buttonContainer) {
      // 为 元素添加 渐变
      buttonContainer.style.transition = "0.6s";
      // 将 按钮移动到 body 下
      document.body.appendChild(buttonContainer);
      // 设置 当前button容器样式
      buttonContainer.style.position = "fixed";
      buttonContainer.style.top = "20px";
      buttonContainer.style.right = "90px";
      buttonContainer.style.margin = "5px";
      buttonContainer.style.padding = "5px";
      buttonContainer.style.background = "white";
      buttonContainer.style.borderRadius = "5px";
      // 设置 按钮样式
      const buttons = buttonContainer.querySelectorAll(
        ".cornerBtn"
      ) as NodeListOf<HTMLElement> | null;
      if (buttons) {
        const firstButton = buttons[0];
        const secondButton = buttons[1];
        const thirdButton = buttons[2];
        // 修改 第一个 样式
        firstButton.style.display = "none";
        // 修改 第二个 样式
        secondButton.style.margin = "0px";
        secondButton.style.padding = "2px 5px";
        secondButton.addEventListener("mouseover", () => {
          secondButton.style.borderRadius = "5px";
          secondButton.style.background = "#13ce66";
          secondButton.style.transition = "0.6s";
        });
        secondButton.addEventListener("mouseleave", () => {
          setTimeout(() => {
            secondButton.style.borderRadius = "0px";
            secondButton.style.background = "white";
            secondButton.style.transition = "0.6s";
          }, 200);
        });
        // 第三个样式
        thirdButton.style.display = "none";
      }
      // 将menuList元素的margin清零
      const menuList = document.querySelector(".menuList") as HTMLElement;
      if (menuList) {
        menuList.style.margin = "0px";
      }
    }
    resolve('');
  });
};

/** 监听 bookmarkmain 滚动事件 */
const onBookmarkmainScroll = () => {
  const bookmarkmain = document.querySelector(
    "#bookmarkmain"
  ) as HTMLElement | null;
  bookmarkmain?.addEventListener("scroll", (e: Event) => {
    // console.log(e);
    const target = e.target as HTMLElement | null;
    if (target && searchInputType === "extension") {
      const scrollTop = target.scrollTop;
      // console.log(scrollTop)
      if (scrollTop > 300) {
        sendMessageToVueComponent("setSearchInputShowStatus", {
          status: false,
        });
      } else {
        sendMessageToVueComponent("setSearchInputShowStatus", { status: true });
      }
    }
  });
};

/** 搜索框组件 */
const createSearchInputComponent = async (ctx: ContentScriptContext) => {
  const ui = await createShadowRootUi(ctx, {
    name: "extension-searchinput-ui",
    position: "overlay",
    zIndex: 1,
    anchor: "body",
    onMount: (container) => {
      // 创建应用
      const app = createApp(SearchInput);
      // 挂载到容器
      app.mount(container);
      return app;
    },
    onRemove: (app) => {
      // 当ui被卸载时，卸载app
      app?.unmount();
    },
  });
  return ui;
};
/** 添加搜索框切换按钮 */
const createSearchInputSwitchButtonComponent = async (
  ctx: ContentScriptContext
) => {
  const ui = await createShadowRootUi(ctx, {
    name: "extension-switchbutton-ui",
    position: "overlay",
    zIndex: 1,
    anchor: "body",
    onMount: (container) => {
      // 创建应用
      const app = createApp(SwitchSearchInput);
      // 挂载到容器
      app.mount(container);
      return app;
    },
    onRemove: (app) => {
      // 当ui被卸载时，卸载app
      app?.unmount();
    },
  });
  return ui;
};
/** 切换 搜索框 */
const switchSearchInput = async () => {
  // 获取当前搜索框元素
  const systemInput = document.querySelector(".search") as HTMLElement;
  // 获取当前搜索框
  const currentSearchInput = (await wxt.storage.getItem(
    `local:${SearchInputMark}`
  )) as SearchInputMarkType | null;
  if (currentSearchInput) {
    // 根据搜索框 类型，显示对应类型的搜索框
    if (currentSearchInput === "system") {
      if (systemInput) {
        systemInput.style.display = "block";
        sendMessageToVueComponent("setSearchInputShowStatus", {
          status: false,
        });
        searchInputType = "system";
      }
    } else {
      if (systemInput) {
        systemInput.style.display = "none";
        sendMessageToVueComponent("setSearchInputShowStatus", { status: true });
        searchInputType = "extension";
      }
    }
  } else {
    // 不存在，则表示当前显示的为 system 搜索框，无需其他操作，但需要将当前搜索框类型 存储到本地
    await wxt.storage.setItem(
      `local:${SearchInputMark}`,
      "system" as SearchInputMarkType
    );
  }
};

/** 壁纸组件 */
const createBizhiComponent = async (ctx: ContentScriptContext) => {
  const ui = await createShadowRootUi(ctx, {
    name: "extension-bizhi-ui",
    position: "overlay",
    zIndex: 1,
    anchor: "body",
    onMount: (container) => {
      // 创建应用
      const app = createApp(BizhiSwiper);
      // 挂载到容器
      app.mount(container);
      return app;
    },
    onRemove: (app) => {
      // 当ui被卸载时，卸载app
      app?.unmount();
    },
  });
  return ui;
};

/** 监听 vue组件 发送的数据 */
const onMessageFromVueComponent = () => {
  // 监听 vue组件中的事件
  window.addEventListener("vue-event", async (e) => {
    let temp = e as Event & { detail: { message: string; data: any } };
    const data = temp.detail;
    // console.log('Received:', data);
    switch (data.message) {
      case "setBackgroundUrl":
        // 获取背景元素的父元素
        let parentElemnt = document.querySelector(
          ".bookmarkmain"
        ) as HTMLElement;
        // 判断当前是否存在 so-main-remove-background-update 元素
        const newElementTemp = parentElemnt.querySelector(
          ".so-main-remove-background-update"
        ) as HTMLElement | null;
        if (newElementTemp) {
          // 如果 存在，则直接设置 当前元素的背景图片的url
          // 对 url 进行处理

          // 更换新元素的 背景图片
          newElementTemp.style.backgroundImage = `url(${convartBgURL(
            data.data.url
          )})`;
          newElementTemp.style.backgroundPosition = "center";
          newElementTemp.style.backgroundSize = "cover";
          newElementTemp.style.height = "100vh";
          newElementTemp.style.transition = "0.6s";
          return;
        }
        // 获取当前背景元素
        let soMainElement = document.querySelector(".so-main") as HTMLElement;
        // 隐藏当前背景元素
        soMainElement.style.transition = "0.6s";
        setTimeout(() => {
          soMainElement.style.display = "none";
        }, 100);
        /** 让 自动更新 background 失效 */
        // 将该元素中所有子元素添加到 div.so-mian 元素中
        const newElemnt = document.createElement("div");
        newElemnt.classList.add("so-main");
        // 添加新元素标识
        newElemnt.classList.add("so-main-remove-background-update");
        // 将所有子元素移动到 新元素中
        const fragment = document.createDocumentFragment();
        while (soMainElement.firstChild) {
          fragment.appendChild(soMainElement.firstChild);
        }
        newElemnt.appendChild(fragment);
        // 将新元素插入到 当前父元素的第一个元素前面
        parentElemnt?.insertBefore(newElemnt, parentElemnt.children[0]);

        // 更换新元素的 背景图片
        if (newElemnt) {
          // console.log(newElemnt.classList)
          // 设置背景样式
          newElemnt.style.backgroundImage = `url(${convartBgURL(
            data.data.url
          )})`;
          newElemnt.style.backgroundPosition = "center";
          newElemnt.style.backgroundSize = "cover";
          newElemnt.style.height = "100vh";
          newElemnt.style.transition = "0.6s";
        }
        break;
      case "setSearchInputStatus":
        const type = data.data.type as SearchInputMarkType | null;
        if (type) {
          await wxt.storage.setItem(`local:${SearchInputMark}`, type);
          await switchSearchInput();
        }
        break;
    }
  });
};
/** 发送数据到 vue组件 */
const sendMessageToVueComponent = (message = "default", data: any = null) => {
  // 创建 自定义 content-script-event 事件
  const event = new CustomEvent("content-script-event", {
    detail: { message, data }, // 传输数据
    bubbles: true, // 允许冒泡
    composed: true, // 穿透 Shadow DOM
  });
  // 全局触发事件
  window.dispatchEvent(event);
};

/** 内容脚本入口 */
export default defineContentScript({
  matches: ["https://www.cangquyun.com/nav"],
  // 设置 cssInjectionMode
  cssInjectionMode: "ui",

  async main(ctx) {
    // 当页面加载之后，在对 页面元素进行操作
    window.onload = async () => {
      setTimeout(async() => {
        // 重置页面样式
        await resetPageStyle().catch((error)=>console.log(error)).finally(()=>{
          /** 监听 bookmarkmain 元素的滚动事件 */
          onBookmarkmainScroll();
        });
      }, 500);

      // 监听 vue 组件中发送的数据
      onMessageFromVueComponent();

      /** 挂载搜索框切换组件 */
      (await createSearchInputSwitchButtonComponent(ctx)).mount();
      /** 挂载搜索框组件 */
      (await createSearchInputComponent(ctx)).mount();
      // 记录当前搜索框状态 或 切换当前搜索框
      await switchSearchInput();

      /** 挂载壁纸组件 */
      (await createBizhiComponent(ctx)).mount();
    };
  },
});
